<template>
  <div class="merchant-info">
    <el-tabs v-model="activeTab">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="handleEditBasic">编辑</el-button>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商家名称">
              {{ basicInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item label="商家类型">
              {{ basicInfo.type }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ basicInfo.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="电子邮箱">
              {{ basicInfo.email }}
            </el-descriptions-item>
            <el-descriptions-item label="营业时间">
              {{ basicInfo.businessHours }}
            </el-descriptions-item>
            <el-descriptions-item label="商家地址">
              {{ basicInfo.address }}
            </el-descriptions-item>
            <el-descriptions-item label="商家简介" :span="2">
              {{ basicInfo.description }}
            </el-descriptions-item>
            <el-descriptions-item label="商家Logo" :span="2">
              <el-image
                v-if="basicInfo.logo"
                :src="basicInfo.logo"
                style="width: 100px; height: 100px"
                :preview-src-list="[basicInfo.logo]"
              />
            </el-descriptions-item>
            <el-descriptions-item label="商家图片" :span="2">
              <el-image
                v-for="(url, index) in basicInfo.images"
                :key="index"
                :src="url"
                style="width: 100px; height: 100px; margin-right: 10px"
                :preview-src-list="basicInfo.images"
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-tab-pane>

      <!-- 资质信息 -->
      <el-tab-pane label="资质信息" name="qualification">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>资质信息</span>
              <el-button type="primary" @click="handleEditQualification">编辑</el-button>
            </div>
          </template>

          <el-descriptions :column="2" border>
            <el-descriptions-item label="营业执照号">
              {{ qualificationInfo.licenseNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="营业执照">
              <el-button type="primary" link @click="handlePreview(qualificationInfo.licenseUrl)">
                查看
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="法人姓名">
              {{ qualificationInfo.legalPerson }}
            </el-descriptions-item>
            <el-descriptions-item label="法人身份证号">
              {{ qualificationInfo.legalPersonId }}
            </el-descriptions-item>
            <el-descriptions-item label="经营许可证号">
              {{ qualificationInfo.operationLicense }}
            </el-descriptions-item>
            <el-descriptions-item label="经营许可证">
              <el-button type="primary" link @click="handlePreview(qualificationInfo.operationLicenseUrl)">
                查看
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="卫生许可证号">
              {{ qualificationInfo.healthLicense }}
            </el-descriptions-item>
            <el-descriptions-item label="卫生许可证">
              <el-button type="primary" link @click="handlePreview(qualificationInfo.healthLicenseUrl)">
                查看
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="其他资质" :span="2">
              <el-table :data="qualificationInfo.otherQualifications" border style="width: 100%">
                <el-table-column prop="name" label="资质名称" />
                <el-table-column prop="number" label="证书编号" />
                <el-table-column prop="expireDate" label="有效期" />
                <el-table-column label="证书文件">
                  <template #default="{ row }">
                    <el-button type="primary" link @click="handlePreview(row.url)">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-tab-pane>

      <!-- 服务范围 -->
      <el-tab-pane label="服务范围" name="service">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>服务范围</span>
              <el-button type="primary" @click="handleEditService">编辑</el-button>
            </div>
          </template>

          <el-descriptions :column="1" border>
            <el-descriptions-item label="服务区域">
              <el-tag
                v-for="area in serviceInfo.areas"
                :key="area"
                class="mx-1"
              >
                {{ area }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="服务类型">
              <el-tag
                v-for="type in serviceInfo.types"
                :key="type"
                class="mx-1"
                type="success"
              >
                {{ type }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="服务说明">
              {{ serviceInfo.description }}
            </el-descriptions-item>
            <el-descriptions-item label="服务时间">
              <el-table :data="serviceInfo.timeSlots" border style="width: 100%">
                <el-table-column prop="day" label="星期" />
                <el-table-column prop="startTime" label="开始时间" />
                <el-table-column prop="endTime" label="结束时间" />
                <el-table-column prop="status" label="状态">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'open' ? 'success' : 'info'">
                      {{ row.status === 'open' ? '营业中' : '休息' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑基本信息对话框 -->
    <el-dialog
      v-model="basicDialogVisible"
      title="编辑基本信息"
      width="600px"
    >
      <el-form
        ref="basicFormRef"
        :model="basicForm"
        :rules="basicRules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="basicForm.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="商家类型" prop="type">
          <el-select v-model="basicForm.type" placeholder="请选择商家类型">
            <el-option label="个人商户" value="individual" />
            <el-option label="企业商户" value="enterprise" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="basicForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="basicForm.email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-picker
            v-model="basicForm.openTime"
            placeholder="开始时间"
            format="HH:mm"
          />
          <span class="mx-2">至</span>
          <el-time-picker
            v-model="basicForm.closeTime"
            placeholder="结束时间"
            format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input v-model="basicForm.address" placeholder="请输入商家地址" />
        </el-form-item>
        <el-form-item label="商家简介" prop="description">
          <el-input
            v-model="basicForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商家简介"
          />
        </el-form-item>
        <el-form-item label="商家Logo" prop="logo">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="basicForm.logo" :src="basicForm.logo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商家图片" prop="images">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="basicDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBasicSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑资质信息对话框 -->
    <el-dialog
      v-model="qualificationDialogVisible"
      title="编辑资质信息"
      width="600px"
    >
      <el-form
        ref="qualificationFormRef"
        :model="qualificationForm"
        :rules="qualificationRules"
        label-width="120px"
      >
        <el-form-item label="营业执照号" prop="licenseNumber">
          <el-input v-model="qualificationForm.licenseNumber" placeholder="请输入营业执照号" />
        </el-form-item>
        <el-form-item label="营业执照" prop="licenseUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleLicenseSuccess"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">上传营业执照</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalPerson">
          <el-input v-model="qualificationForm.legalPerson" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人身份证号" prop="legalPersonId">
          <el-input v-model="qualificationForm.legalPersonId" placeholder="请输入法人身份证号" />
        </el-form-item>
        <el-form-item label="经营许可证号" prop="operationLicense">
          <el-input v-model="qualificationForm.operationLicense" placeholder="请输入经营许可证号" />
        </el-form-item>
        <el-form-item label="经营许可证" prop="operationLicenseUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleOperationLicenseSuccess"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">上传经营许可证</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="卫生许可证号" prop="healthLicense">
          <el-input v-model="qualificationForm.healthLicense" placeholder="请输入卫生许可证号" />
        </el-form-item>
        <el-form-item label="卫生许可证" prop="healthLicenseUrl">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="handleHealthLicenseSuccess"
            :before-upload="beforeUpload"
          >
            <el-button type="primary">上传卫生许可证</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="其他资质">
          <div v-for="(item, index) in qualificationForm.otherQualifications" :key="index" class="qualification-item">
            <el-input v-model="item.name" placeholder="资质名称" class="mr-2" />
            <el-input v-model="item.number" placeholder="证书编号" class="mr-2" />
            <el-date-picker
              v-model="item.expireDate"
              type="date"
              placeholder="有效期"
              class="mr-2"
            />
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-success="(res) => handleOtherQualificationSuccess(res, index)"
              :before-upload="beforeUpload"
            >
              <el-button type="primary">上传证书</el-button>
            </el-upload>
            <el-button type="danger" link @click="handleRemoveQualification(index)">
              删除
            </el-button>
          </div>
          <el-button type="primary" @click="handleAddQualification">添加资质</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="qualificationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleQualificationSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑服务范围对话框 -->
    <el-dialog
      v-model="serviceDialogVisible"
      title="编辑服务范围"
      width="600px"
    >
      <el-form
        ref="serviceFormRef"
        :model="serviceForm"
        :rules="serviceRules"
        label-width="100px"
      >
        <el-form-item label="服务区域" prop="areas">
          <el-select
            v-model="serviceForm.areas"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入服务区域"
          >
            <el-option
              v-for="item in areaOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="types">
          <el-select
            v-model="serviceForm.types"
            multiple
            placeholder="请选择服务类型"
          >
            <el-option
              v-for="item in serviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务说明" prop="description">
          <el-input
            v-model="serviceForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入服务说明"
          />
        </el-form-item>
        <el-form-item label="服务时间">
          <div v-for="(item, index) in serviceForm.timeSlots" :key="index" class="time-slot-item">
            <el-select v-model="item.day" placeholder="星期" class="mr-2">
              <el-option label="周一" value="monday" />
              <el-option label="周二" value="tuesday" />
              <el-option label="周三" value="wednesday" />
              <el-option label="周四" value="thursday" />
              <el-option label="周五" value="friday" />
              <el-option label="周六" value="saturday" />
              <el-option label="周日" value="sunday" />
            </el-select>
            <el-time-picker
              v-model="item.startTime"
              placeholder="开始时间"
              format="HH:mm"
              class="mr-2"
            />
            <el-time-picker
              v-model="item.endTime"
              placeholder="结束时间"
              format="HH:mm"
              class="mr-2"
            />
            <el-select v-model="item.status" placeholder="状态" class="mr-2">
              <el-option label="营业中" value="open" />
              <el-option label="休息" value="closed" />
            </el-select>
            <el-button type="danger" link @click="handleRemoveTimeSlot(index)">
              删除
            </el-button>
          </div>
          <el-button type="primary" @click="handleAddTimeSlot">添加时间段</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleServiceSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantInfo,
  updateMerchantBasic,
  updateMerchantQualification,
  updateMerchantService
} from '@/api/merchant'

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息
const basicInfo = reactive({})
const basicDialogVisible = ref(false)
const basicFormRef = ref(null)
const basicForm = reactive({
  name: '',
  type: '',
  phone: '',
  email: '',
  openTime: '',
  closeTime: '',
  address: '',
  description: '',
  logo: '',
  images: []
})

// 资质信息
const qualificationInfo = reactive({})
const qualificationDialogVisible = ref(false)
const qualificationFormRef = ref(null)
const qualificationForm = reactive({
  licenseNumber: '',
  licenseUrl: '',
  legalPerson: '',
  legalPersonId: '',
  operationLicense: '',
  operationLicenseUrl: '',
  healthLicense: '',
  healthLicenseUrl: '',
  otherQualifications: []
})

// 服务范围
const serviceInfo = reactive({})
const serviceDialogVisible = ref(false)
const serviceFormRef = ref(null)
const serviceForm = reactive({
  areas: [],
  types: [],
  description: '',
  timeSlots: []
})

// 表单验证规则
const basicRules = {
  name: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择商家类型', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入商家地址', trigger: 'blur' }]
}

const qualificationRules = {
  licenseNumber: [{ required: true, message: '请输入营业执照号', trigger: 'blur' }],
  licenseUrl: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  legalPerson: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }],
  legalPersonId: [{ required: true, message: '请输入法人身份证号', trigger: 'blur' }]
}

const serviceRules = {
  areas: [{ required: true, message: '请选择服务区域', trigger: 'change' }],
  types: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入服务说明', trigger: 'blur' }]
}

// 选项数据
const areaOptions = [
  '东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区',
  '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区'
]

const serviceTypeOptions = [
  { label: '洗衣服务', value: 'laundry' },
  { label: '干洗服务', value: 'drycleaning' },
  { label: '皮具护理', value: 'leather' },
  { label: '鞋类护理', value: 'shoes' },
  { label: '家居清洁', value: 'housekeeping' }
]

// 上传地址
const uploadUrl = '/api/merchant/upload'

// 获取商家信息
const getInfo = async () => {
  try {
    const { data } = await getMerchantInfo()
    Object.assign(basicInfo, data.basic)
    Object.assign(qualificationInfo, data.qualification)
    Object.assign(serviceInfo, data.service)
  } catch (error) {
    console.error('获取商家信息失败:', error)
    ElMessage.error('获取商家信息失败')
  }
}

// 编辑基本信息
const handleEditBasic = () => {
  Object.assign(basicForm, basicInfo)
  basicDialogVisible.value = true
}

// 提交基本信息
const handleBasicSubmit = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    await updateMerchantBasic(basicForm)
    ElMessage.success('保存成功')
    basicDialogVisible.value = false
    getInfo()
  } catch (error) {
    console.error('保存基本信息失败:', error)
  }
}

// 编辑资质信息
const handleEditQualification = () => {
  Object.assign(qualificationForm, qualificationInfo)
  qualificationDialogVisible.value = true
}

// 提交资质信息
const handleQualificationSubmit = async () => {
  if (!qualificationFormRef.value) return
  
  try {
    await qualificationFormRef.value.validate()
    await updateMerchantQualification(qualificationForm)
    ElMessage.success('保存成功')
    qualificationDialogVisible.value = false
    getInfo()
  } catch (error) {
    console.error('保存资质信息失败:', error)
  }
}

// 编辑服务范围
const handleEditService = () => {
  Object.assign(serviceForm, serviceInfo)
  serviceDialogVisible.value = true
}

// 提交服务范围
const handleServiceSubmit = async () => {
  if (!serviceFormRef.value) return
  
  try {
    await serviceFormRef.value.validate()
    await updateMerchantService(serviceForm)
    ElMessage.success('保存成功')
    serviceDialogVisible.value = false
    getInfo()
  } catch (error) {
    console.error('保存服务范围失败:', error)
  }
}

// 添加资质
const handleAddQualification = () => {
  qualificationForm.otherQualifications.push({
    name: '',
    number: '',
    expireDate: '',
    url: ''
  })
}

// 删除资质
const handleRemoveQualification = (index) => {
  qualificationForm.otherQualifications.splice(index, 1)
}

// 添加时间段
const handleAddTimeSlot = () => {
  serviceForm.timeSlots.push({
    day: '',
    startTime: '',
    endTime: '',
    status: 'open'
  })
}

// 删除时间段
const handleRemoveTimeSlot = (index) => {
  serviceForm.timeSlots.splice(index, 1)
}

// 预览文件
const handlePreview = (url) => {
  window.open(url)
}

// Logo上传成功
const handleLogoSuccess = (response) => {
  basicForm.logo = response.url
}

// Logo上传前校验
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleImageSuccess = (response) => {
  basicForm.images.push(response.url)
}

// 图片上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 营业执照上传成功
const handleLicenseSuccess = (response) => {
  qualificationForm.licenseUrl = response.url
}

// 经营许可证上传成功
const handleOperationLicenseSuccess = (response) => {
  qualificationForm.operationLicenseUrl = response.url
}

// 卫生许可证上传成功
const handleHealthLicenseSuccess = (response) => {
  qualificationForm.healthLicenseUrl = response.url
}

// 其他资质上传成功
const handleOtherQualificationSuccess = (response, index) => {
  qualificationForm.otherQualifications[index].url = response.url
}

// 文件上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage && !isPDF) {
    ElMessage.error('只能上传图片或PDF文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

onMounted(() => {
  getInfo()
})
</script>

<style lang="scss" scoped>
.merchant-info {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .qualification-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .mr-2 {
      margin-right: 10px;
    }
  }

  .time-slot-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .mr-2 {
      margin-right: 10px;
    }
  }

  .mx-1 {
    margin: 0 4px;s
  }

  .mx-2 {
    margin: 0 8px;
  }
}
</style> 